package com.bnlr.lrparking.widget.photo;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.util.ScannerUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 图片预览
 */
public class PhotoViewerActivity extends BaseActivity {
    @BindView(R.id.photo_viewer_index)
    TextView tvIndex;
    @BindView(R.id.photo_viewer_back)
    ImageView ivBack;
    @BindView(R.id.photo_viewer_viewpager)
    ViewPager viewPager;
    @BindView(R.id.photo_viewer_save)
    TextView tvSave;
    public static final String PHOTO_VIEWER_TAG = "PhotoViewerActivity";
    private PhotoViewerAdapter viewerAdapter;
    private PhotoViewerBean photoViewerBean;
    private Unbinder unbinder;
    private int selectIndex;
    private  ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_viewer);
        unbinder = ButterKnife.bind(this);
        Intent intent = getIntent();
        photoViewerBean =  intent.getParcelableExtra(PHOTO_VIEWER_TAG);
        if (photoViewerBean != null) {
            final int photoTotal = photoViewerBean.getPhotos().size();
            viewerAdapter = new PhotoViewerAdapter(this,photoViewerBean.getPhotos());
            viewPager.setOffscreenPageLimit(4);
            viewPager.setAdapter(viewerAdapter);
            viewPager.setCurrentItem(photoViewerBean.getPositionIndex());
            selectIndex = photoViewerBean.getPositionIndex();
            tvIndex.setText((photoViewerBean.getPositionIndex()+1)+"/"+ photoTotal);
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }
                @Override
                public void onPageSelected(int position) {
                    selectIndex=position;
                    tvIndex.setText((position+1)+"/"+ photoTotal);

                }
                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

        }
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String url=photoViewerBean.getPhotos().get(selectIndex);
                PermissionUtils.permission("android.permission.READ_EXTERNAL_STORAGE","android.permission.WRITE_EXTERNAL_STORAGE")
                        .callback(new PermissionUtils.SimpleCallback() {
                            @Override
                            public void onGranted() {
                                saveBitmap(url);
                            }
                            @Override
                            public void onDenied() {
                                ToastUtils.showShort("请打开相应权限，进行存储操作");
                            }
                        }).request();

            }
        });
    }
    /**
     * 保存
     * @param url
     */
    public void saveBitmap(final String url) {
        loadingDialog= ProgressDialog.show(this,null , "正在保存中...");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File appDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/ruipai/");
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    //获取内部存储状态
                    String state = Environment.getExternalStorageState();
                    //如果状态不是mounted，无法读写
                    if (!state.equals(Environment.MEDIA_MOUNTED)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loadingDialog.dismiss();
                                Toast.makeText(PhotoViewerActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                            }
                        });

                        return;
                    }
                    String fileName = System.currentTimeMillis()+"";
                    Bitmap mBitmap;
                    URL fileUrl=new URL(url);

                    HttpURLConnection conn;
                    conn = (HttpURLConnection) fileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    mBitmap = BitmapFactory.decodeStream(is);

                    final File file = new File(appDir + (fileName + ".jpg"));
                    FileOutputStream out = new FileOutputStream(file);
                    mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    conn.disconnect();
                    //通知更新
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                        // 最后通知图库更新
                        try {
                            ScannerUtils.ScannerByMedia(PhotoViewerActivity.this,file.getAbsolutePath());
                        }catch (Exception e){

                        }

                    }else {
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        sendBroadcast(intent);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingDialog.dismiss();
                            Toast.makeText(PhotoViewerActivity.this, "已保存到手机", Toast.LENGTH_SHORT).show();
                        }
                    });
                    if (loadingDialog!=null){
                        loadingDialog.dismiss();
                    }
                } catch (Exception e) {
                    loadingDialog.dismiss();
                    e.printStackTrace();
                }
            }
        }).start();


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
